package com.zhss.security.demospringsecurity.config;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName KaptchaAuthenticationProvider
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/12 22:46
 * @Version 1.0
 */
public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		final HttpServletRequest request =
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		final String attribute = (String)request.getSession().getAttribute("kaptcha");
		final String kaptcha = request.getParameter("kaptcha");
		if (kaptcha != null && attribute != null && kaptcha.equalsIgnoreCase(attribute)) {
			return super.authenticate(authentication);
		} else {
			throw new AuthenticationServiceException("验证码错误");
		}
	}
}
